package com.zy.extract;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

public class ExtractUI extends JFrame {
	private static final long serialVersionUID = 1L;
	private static ExtractUI frame;

	private JPanel contentPane;
	private JTextField sourcePath;
	private JTextField outPath;
	private JTextField textIgnore;
	private JTextField textkeyFile;
	private JLabel lblNewLabel_1;
	private JLabel resultMsg;
	private JScrollPane scrollPane;
	private JTextArea resultArea;

	private JButton btnOutPath;
	private JButton btnAnalysis;
	private JButton btnKeyFile;

	private JButton btnSaveResult;
	private JButton btnSaveWord;
	private JButton btnCheck;
	private JButton btnReplace;
	private JButton btnKeyReplace;

	// 非中文的字符范围
	// private static String REG_CN = "[^\u4e00-\u9fa5]";
	// 中文的字符范围
	private static String REG_CN = "[\u4e00-\u9fa5]";
	private static Pattern pattern_cn = Pattern.compile(REG_CN);
	// 双引号
	private static Pattern pattern_symbol1 = Pattern.compile("\"(.*?)\"");
	// 单引号
	private static Pattern pattern_symbol2 = Pattern.compile("'(.*?)'");
	// ></间
	private static Pattern pattern_symbol3 = Pattern.compile(">(.*?)</");
	// private static Pattern pattern_symbol3 = Pattern.compile(">\\[^\\]</");

	// 提示区信息
	private StringBuilder sb = new StringBuilder();
	// 检查文件总数
	private long allFileNumber = 0;
	// 有中文文件数
	private long fileNumber = 0;
	// 有中文词数
	private long wordNumber = 0;
	// 有问题中文词数
	private long wordProblemNumber = 0;
	// 去重后的单词
	private Set<String> setWord = new HashSet<String>();

	private HashMap<String, String> wordKeys = new HashMap<String, String>();
	// 是否分析
	private boolean isAnalysis = false;

	// key中 数字长度
	private int KEY_NUMBER_LENGTH = 4;

	// 是否校验通过
	// private boolean isCheckPass = false;
	private List<String> ignoreList = new ArrayList<String>();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		frame = new ExtractUI();
		frame.setVisible(true);
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				try {
//					frame = new ExtractUI();
//					frame.setVisible(true);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});

	}

	/**
	 * Create the frame.
	 */
	public ExtractUI() {
		setResizable(false);

		setTitle("中文查找/前端多语言替换工具 V1.4.0_一次替换版");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1011, 654);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblNewLabel = new JLabel("查找文件/目录：");
		lblNewLabel.setBounds(10, 13, 107, 22);
		contentPane.add(lblNewLabel);

		sourcePath = new JTextField();
		sourcePath.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				try {
					frame.textchange();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

		});

		sourcePath.setBounds(115, 10, 765, 28);
		contentPane.add(sourcePath);
		sourcePath.setColumns(10);

		JButton btnSourcePath = new JButton("选择...");
		btnSourcePath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.getPath(true);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		btnSourcePath.setBounds(890, 10, 97, 29);
		contentPane.add(btnSourcePath);

		lblNewLabel_1 = new JLabel("结果输出文件：");
		lblNewLabel_1.setBounds(10, 46, 107, 22);
		contentPane.add(lblNewLabel_1);

		outPath = new JTextField();
		outPath.setColumns(10);
		outPath.setBounds(115, 43, 765, 28);
		contentPane.add(outPath);

		btnOutPath = new JButton("选择...");
		btnOutPath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				try {
					frame.getPath(false);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		btnOutPath.setBounds(890, 43, 97, 29);
		contentPane.add(btnOutPath);

		btnAnalysis = new JButton("分  析");
		btnAnalysis.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.analysis();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		btnAnalysis.setBounds(115, 169, 97, 23);
		contentPane.add(btnAnalysis);

		resultMsg = new JLabel("");
		resultMsg.setFont(new Font("宋体", Font.BOLD, 14));
		resultMsg.setForeground(Color.RED);
		resultMsg.setBounds(10, 578, 977, 29);
		contentPane.add(resultMsg);

		btnSaveResult = new JButton("分析结果另存为...");
		btnSaveResult.setEnabled(false);
		btnSaveResult.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.saveResult();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		btnSaveResult.setBounds(239, 169, 141, 23);
		contentPane.add(btnSaveResult);

		btnSaveWord = new JButton("保存单词");
		btnSaveWord.setEnabled(false);
		btnSaveWord.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.saveWord();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		btnSaveWord.setBounds(425, 169, 97, 23);
		contentPane.add(btnSaveWord);

		scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 202, 977, 366);
		contentPane.add(scrollPane);

		resultArea = new JTextArea();
		scrollPane.setViewportView(resultArea);
		resultArea.setColumns(30);

		btnReplace = new JButton("全部替换");
		btnReplace.setToolTipText("分析并校验完成后才能使用");
		btnReplace.setEnabled(false);
		btnReplace.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.replaceAll();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		btnReplace.setBounds(715, 169, 97, 23);
		contentPane.add(btnReplace);

		btnCheck = new JButton("校验");
		btnCheck.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.check();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		btnCheck.setBounds(561, 169, 114, 23);
		contentPane.add(btnCheck);

		JLabel lblIgnore = new JLabel("忽略文件(,分隔)：");
		lblIgnore.setBounds(10, 120, 107, 24);
		contentPane.add(lblIgnore);

		textIgnore = new JTextField();
		textIgnore.setBounds(115, 117, 765, 32);
		contentPane.add(textIgnore);
		textIgnore.setColumns(10);

		JLabel lblkeyFle = new JLabel("已有Key文件：");
		lblkeyFle.setBounds(10, 82, 107, 22);
		contentPane.add(lblkeyFle);

		textkeyFile = new JTextField();
		textkeyFile.setColumns(10);
		textkeyFile.setBounds(115, 79, 765, 28);
		contentPane.add(textkeyFile);

		btnKeyFile = new JButton("选择...");
		btnKeyFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.selectKeyFile();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		btnKeyFile.setBounds(890, 79, 97, 29);
		contentPane.add(btnKeyFile);

		btnKeyReplace = new JButton("用key替换");
		btnKeyReplace.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					frame.keyReplace();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		btnKeyReplace.setBounds(822, 169, 97, 23);
		contentPane.add(btnKeyReplace);
	}

	private void textchange() throws IOException {
		String sourceFile = sourcePath.getText();
		if (sourceFile == null || sourceFile.trim().length() == 0) {
			return;
		}
		String out = outPath.getText();
		if (out == null || out.trim().length() == 0) {
			File file = new File(sourceFile);
			if (file.isFile()) {
				int p = sourceFile.lastIndexOf(".");
				if (p >= 0) {
					outPath.setText(sourceFile.trim().substring(0, p) + "_result.txt");
				}
			} else {
				outPath.setText(sourceFile.trim() + File.separator + "result.txt");
			}
		}
	}

	private void getPath(boolean isSoure) throws IOException {

		String title = isSoure ? "选择检查文件夹" : "选择输出文件夹";

		JFileChooser jFileChooser = new JFileChooser();
		jFileChooser.setToolTipText(title);
		jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		jFileChooser.setMultiSelectionEnabled(false);

		jFileChooser.showOpenDialog(null);
		File file = jFileChooser.getSelectedFile();
		if (file != null) {
			if (isSoure) {
				sourcePath.setText(file.getAbsolutePath());
				String out = outPath.getText();
				if (out == null || out.trim().length() == 0) {
					outPath.setText(file.getAbsolutePath() + File.separator + "result.txt");
				}
			} else {
				outPath.setText(file.getAbsolutePath() + File.separator + "result.txt");
			}
		}
	}

	private void selectKeyFile() throws IOException {
		JFileChooser jFileChooser = new JFileChooser();
		jFileChooser.setToolTipText("选择已经有的Key文件");
		jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		jFileChooser.setMultiSelectionEnabled(false);

		jFileChooser.setFileFilter(new FileNameExtensionFilter("选择js文件", "js"));

		jFileChooser.showOpenDialog(null);
		File file = jFileChooser.getSelectedFile();
		if (file != null) {
			textkeyFile.setText(file.getAbsolutePath());
		}
	}

	/**
	 * 用key替换
	 * 
	 * @throws Exception
	 */
	private void keyReplace() throws Exception {

		String keyTxt = textkeyFile.getText();

		if (keyTxt == null || keyTxt.trim().length() == 0) {
			resultMsg.setText("请先选择替换使用的key文件！");
			return;
		}
		File keyFile = new File(keyTxt);
		if (!keyFile.exists()) {
			resultMsg.setText("key文件不存在！");
			return;
		}
		if (keyFile.isDirectory()) {
			resultMsg.setText("key文件是目录不是文件，请选择文件！");
			return;
		}

		String sourceFile = sourcePath.getText();
		if (sourceFile == null || sourceFile.trim().length() == 0) {
			resultMsg.setText("请先选择查找文件目录！");
			return;
		}
		resultArea.setText("开始处理...");

		allFileNumber = 0;
		fileNumber = 0;
		sb.setLength(0);
		btnKeyReplace.setEnabled(false);

		new Thread(new Runnable() {
			public void run() {
				try {
					readkey(keyTxt);
					replaceAllFile(sourceFile.trim());

					StringBuilder sbMsg = new StringBuilder();
					sbMsg.append("文件数总：").append(allFileNumber).append(", ");
					sbMsg.append("有中文文件数：").append(fileNumber).append(". ");

					resultMsg.setText("处理完成！" + sbMsg.toString());

					btnKeyReplace.setEnabled(true);

					String out = outPath.getText();
					if (out == null || out.trim().length() == 0) {
						out = sourceFile.trim() + File.separator;
					}
					int p = out.lastIndexOf(File.separator);
					if (p >= 0) {
						out = out.substring(0, p) + File.separator + "ReplaseResult.txt";
						File fileOut = new File(out);
						outPath.setText(fileOut.getAbsolutePath());
						outFile(fileOut, sb.toString());
					}

				} catch (IOException e) {
					e.printStackTrace();
					btnKeyReplace.setEnabled(true);
				}
			}
		}).start();

		// btnKeyReplace.setEnabled(true);
	}

	private String readkey(String keyFile) {
		wordKeys.clear();

		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		StringBuilder allFile = new StringBuilder();

		try {
			fis = new FileInputStream(keyFile);
			isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			boolean isAnnotate = false;

			String key = "";
			String word = "";

			while ((line = br.readLine()) != null) {
				allFile.append(line).append("\n");
				line = line.trim();
				if (line.contains("//")) {
					continue;
				}
				if (line.startsWith("<!--")) {
					if (!line.endsWith("-->")) {
						isAnnotate = true;
					}
					continue;
				} else if (line.startsWith("/**")) {
					if (!line.endsWith("*/")) {
						isAnnotate = true;
					}
					continue;
				} else if (line.startsWith("/*")) {
					if (!line.endsWith("*/")) {
						isAnnotate = true;
					}
					continue;
				}
				if (isAnnotate) {
					int p = line.indexOf("-->");
					if (p >= 0) {
						isAnnotate = false;
					} else {
						p = line.indexOf("*/");
						if (p >= 0) {
							isAnnotate = false;
						}
					}
					continue;
				}
				int p = line.indexOf(":");
				// 如果key文件换行，将有问题
				if (p >= 0) {
					key = line.substring(0, p).trim();
					word = line.substring(p + 1).trim();
					if (word.startsWith("'")) {
						word = word.substring(1);
						int p1 = word.lastIndexOf("'");
						word = word.substring(0, p1);
					} else if (word.startsWith("\"")) {
						word = word.substring(1);
						int p1 = word.lastIndexOf("\"");
						word = word.substring(0, p1);
					}
					wordKeys.put(word, key);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return allFile.toString();
	}

	/**
	 * 分析
	 * 
	 * @throws IOException
	 */
	private void analysis() throws IOException {
		isAnalysis = false;
		resultMsg.setText("");
		sb.setLength(0);
		resultArea.setText("");

		fileNumber = 0;
		wordNumber = 0;
		wordProblemNumber = 0;
		setWord.clear();
		String sourceFile = sourcePath.getText();

		if (sourceFile == null || sourceFile.trim().length() == 0) {
			resultMsg.setText("请先选择要分析的文件目录！");
			return;
		}

		btnAnalysis.setEnabled(false);

		doIgnore();

		new Thread(new Runnable() {
			public void run() {
				try {
					analysis(sourceFile.trim());

					resultArea.setText(sb.toString());

					StringBuilder sbMsg = new StringBuilder();
					sbMsg.append("检查文件数：").append(allFileNumber).append(", ");
					sbMsg.append("有中文文件数：").append(fileNumber).append(", ");
					sbMsg.append("正常中文词数：").append(wordNumber).append(".");
					sbMsg.append("有问题的中文词数：").append(wordProblemNumber).append(".");
					sbMsg.append("去重后正常中文词数：").append(setWord.size()).append(".");

					resultMsg.setText(sbMsg.toString());
					isAnalysis = true;

					String out = outPath.getText();
					if (out != null && out.trim().length() > 0) {

						File fileOut = new File(out);
						outFile(fileOut, sbMsg.append("\n").append(sb).toString());
					}
					btnSaveResult.setEnabled(true);
					btnSaveWord.setEnabled(true);
					btnCheck.setEnabled(true);

				} catch (IOException e) {
					e.printStackTrace();
					btnAnalysis.setEnabled(true);
				}
				btnAnalysis.setEnabled(true);
			}
		}).start();

//		analysis(sourceFile);

//		resultArea.setText(sb.toString());
//
//		StringBuilder sbMsg = new StringBuilder();
//		sbMsg.append("检查文件数：").append(allFileNumber).append(", ");
//		sbMsg.append("有中文文件数：").append(fileNumber).append(", ");
//		sbMsg.append("正常中文词数：").append(wordNumber).append(".");
//		sbMsg.append("有问题的中文词数：").append(wordProblemNumber).append(".");
//		sbMsg.append("去重后正常中文词数：").append(setWord.size()).append(".");
//
//		resultMsg.setText(sbMsg.toString());
//		isAnalysis = true;
//
//		String out = outPath.getText();
//		if (out != null && out.trim().length() > 0) {
//
//			File fileOut = new File(out);
//			outFile(fileOut, sbMsg.append("\n").append(sb).toString());
//		}
//		btnSaveResult.setEnabled(true);
//		btnSaveWord.setEnabled(true);
//		btnCheck.setEnabled(true);
		// btnReplace.setEnabled(true);
	}

	private void analysis(String path) throws IOException {

		File file = new File(path);
//		if(file.isFile()) {
//			analysisFile(file.getCanonicalPath());
//			return;
//		}
		if (checkIgnore(path)) {
			return;
		}
		if (file.isFile()) {
			analysisFile(file.getCanonicalPath());
		} else {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {

				if (files[i].isDirectory()) {
					analysis(files[i].toString());
				} else {
					if (!files[i].isDirectory()) {
						String fileName = files[i].getName();
						String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
						if (fileType.equalsIgnoreCase("vue") || fileType.equalsIgnoreCase("js") || fileType.equalsIgnoreCase("java")) {
							analysisFile(files[i].getCanonicalPath());
						}
					}
				}
			}
		}

	}

	private void analysisFile(String path) throws IOException {

		if (checkIgnore(path)) {
			return;
		}
		resultMsg.setText("正在分析：" + path);

		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		// 当前文件中的中文
		StringBuilder sbFile = new StringBuilder();
		// 当前文件中的可替换中文数
		long thisWordNumber = 0;
		// 当前文件中的不可替换中文数
		long thisFileNotReplaceWordNumber = 0;
		// 搜索到的文件数
		allFileNumber = allFileNumber + 1;

		ArrayList<String> words = new ArrayList<String>();
		try {
			fis = new FileInputStream(path);
			isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			boolean isAnnotate = false;
			while ((line = br.readLine()) != null) {
				line = line.trim();
				if (isIgnoreLine(line)) {
					continue;
				}
				if (line.startsWith("<!--")) {
					if (!line.endsWith("-->")) {
						isAnnotate = true;
					}
					continue;
				} else if (line.startsWith("/**")) {
					if (!line.endsWith("*/")) {
						isAnnotate = true;
					}
					continue;
				} else if (line.startsWith("/*")) {
					if (!line.endsWith("*/")) {
						isAnnotate = true;
					}
					continue;
				}
				if (isAnnotate) {
					int p = line.indexOf("-->");
					if (p >= 0) {
						isAnnotate = false;
					} else {
						p = line.indexOf("*/");
						if (p >= 0) {
							isAnnotate = false;
						}
					}
					continue;
				}
				// line = line.replaceAll(REG_CN, "");
				words.clear();
				words = getLineWord(line, words);

				if (words.size() > 0) {
					// System.out.println(line);
					for (String word : words) {
						int p = line.indexOf(word);
						if (p >= 0) {
							String beforline = line.substring(0, p).trim();
							String afterline = line.substring(p + word.length()).trim();
							String errReason = "";
							errReason = getErrorReason(beforline, afterline, errReason);
							if (errReason.length() == 0) {
								sbFile.append(word);
								sbFile.append("\n");
								wordNumber = wordNumber + 1;
								thisWordNumber = thisWordNumber + 1;
								setWord.add(word);
							} else {
								sbFile.append(word).append(errReason);
								wordProblemNumber = wordProblemNumber + 1;
								thisFileNotReplaceWordNumber = thisFileNotReplaceWordNumber + 1;
								sbFile.append("\n");
							}
						}
					}
				}
			}
			if (sbFile.length() > 0) {
				fileNumber = fileNumber + 1;
				sb.append(path).append(" ").append(", 含可替换中文数：").append(thisWordNumber).append(", 含不可替换中文数：").append(thisFileNotReplaceWordNumber);
				sb.append("\n");
				sb.append(sbFile);
				sb.append("\n");

				resultArea.setText(sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private boolean isIgnoreLine(String line) {

		if (line.startsWith("//") || line.startsWith("*") || line.startsWith("console.") || line.startsWith("@Api") || line.startsWith("log.")
		// || line.startsWith("@ApiOperation") || line.startsWith("@ApiModelProperty")
		// || line.startsWith("@ApiModel") || line.startsWith("@ApiParam") ||
		// line.startsWith("@ApiModel")
				|| line.startsWith("description = ")) {
			return true;
		}
		return false;
	}

	/**
	 * 提取忽略文件列表
	 */
	private void doIgnore() {
		// ignoreList
		String ignoreFiles = textIgnore.getText();
		if (null == ignoreFiles || "".equals(ignoreFiles.trim())) {
			return;
		}

		StringTokenizer st = new StringTokenizer(ignoreFiles, ",|，/", true);
		Vector<String> vs = new Vector<String>();
		while (st.hasMoreTokens()) {
			vs.add(st.nextToken());
		}
		int size = vs.size();
		String temp = "";
		for (int i = 0; i < size; i++) {
			temp = vs.get(i).trim();

			if (",".equals(temp) || "|".equals(temp) || "，".equals(temp) || "/".equals(temp)) {
				continue;
			}
			ignoreList.add(temp);
		}

	}

	/**
	 * 检查是否忽略文件
	 */
	private boolean checkIgnore(String path) {

		// 默认忽略多语言文件
		if (path.endsWith("lang" + File.separator + "zh.js") || path.endsWith("lang" + File.separator + "en.js")) {
			return true;
		}

		// 考虑多个同名文件情况，只要路径不同就可以分开
		for (String igonre : ignoreList) {
			if (path.lastIndexOf(igonre) >= 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 单行里面找出所有的中文
	 * 
	 * @param line
	 * @return
	 */
	private ArrayList<String> getLineWord(String line, ArrayList<String> words) {

		int p = line.indexOf("//");

		if (p >= 0) {
			// 去掉后注释部分
			line = line.substring(0, p);
		}

		// 先处理单、双引号以及><里面的中文
		line = getLinemarksWord(line, words);

		StringBuilder sb = new StringBuilder();
		String s = "";
		char[] charArray = line.toCharArray();
		for (int i = 0; i < charArray.length; i++) {
			s = String.valueOf(charArray[i]);
			if (isChinese(s)) {
				sb.append(s);
			} else {
				if (sb.length() > 0) {
					words.add(sb.toString());
				}
				sb = new StringBuilder();
			}
		}
		if (sb.length() > 0) {
			words.add(sb.toString());
		}

		return words;
	}

	/**
	 * 先处理单、双引号以及><里面的中文
	 * 
	 * @param line
	 * @return
	 */
	private String getLinemarksWord(String line, ArrayList<String> words) {
		Matcher m = pattern_symbol1.matcher(line);
		String temp = "";
		String word = "";
		int start = 0;
		int end = 0;
		ArrayList<String> replaces = new ArrayList<String>();
		while (m.find()) {
			start = m.start();
			end = m.end();
			temp = line.substring(start, end);
			word = line.substring(start + 1, end - 1).trim();
			if (isChinese(word)) {
				// 可能双引号里面带单引号 column-cell :data="{'label':'净利润', 'value': isMonthData ?
				// kpiData.plamttm : kpiData.plamt, 'unit': '万'}"></column-cell>

				if (word.trim().indexOf("'") >= 0) {
					getLineWord(word, words);
				} else {
					words.add(word);
				}
				replaces.add(temp);
			}
		}
		for (String replace : replaces) {
			line = line.replace(replace, "");
		}
		replaces.clear();
		Matcher m2 = pattern_symbol2.matcher(line);
		while (m2.find()) {
			start = m2.start();
			end = m2.end();
			temp = line.substring(start, end);
			word = line.substring(start + 1, end - 1).trim();
			if (isChinese(word)) {
				if (word.trim().indexOf("\"") >= 0) {
					getLineWord(word, words);
				} else {
					words.add(word);
				}
				replaces.add(temp);
			}
		}
		for (String replace : replaces) {
			line = line.replace(replace, "");
		}
		replaces.clear();
		// 处理 >< 直接的内容
		Matcher m3 = pattern_symbol3.matcher(line);
		while (m3.find()) {
			start = m3.start();
			end = m3.end();
			temp = line.substring(start, end);
			word = line.substring(start + 1, end - 2).trim();
			if (isChinese(word)) {
				// <div class=\"top-font\"><span class=\"font-color\" style=\"color:
				// #996400;\">合计</span><span>销售额</span></div>
				// 处理 结果可能为 <span>销售额的问题
				int p1 = word.indexOf("<");
				int p2 = word.indexOf(">");

				if (p1 > -1 && p2 > -1 && p2 > p1) {
					word = word.substring(0, p1) + word.substring(p2 + 1);
				}

				// <span class="table_title">{{ `门店${datetype === 'M' ? '月累计':'日'}净利润排行`
				// }}</span>

				if (word.trim().indexOf("{") > -1 || word.indexOf("'") > -1 || word.indexOf("\"") > -1 || word.indexOf("`") > -1) {
					getLineWord(word, words);
				} else {
					words.add(word);
				}
				replaces.add(temp);
			}
		}
		for (String replace : replaces) {
			line = line.replace(replace, "");
		}

		return line;

	}

	private boolean isChinese(String s) {
		Matcher m = pattern_cn.matcher(s);
		return m.find();

	}

	/**
	 * 保存结果
	 * 
	 * @throws IOException
	 */
	private void saveResult() throws IOException {
		if (!isAnalysis) {
			resultMsg.setText("请先分析，再输出");
			return;
		}

		JFileChooser jFileChooser = new JFileChooser();
		jFileChooser.setToolTipText("选择结果输出文件");
		jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		jFileChooser.setMultiSelectionEnabled(false);

		jFileChooser.showOpenDialog(null);
		File file = jFileChooser.getSelectedFile();
		if (file != null) {
			outFile(file, sb.toString());
		}
	}

	/**
	 * 保存单词
	 * 
	 * @throws IOException
	 */
	private void saveWord() throws Exception {

		if (!isAnalysis) {
			resultMsg.setText("请先分析，再输出");
			return;
		}

		JFileChooser jFileChooser = new JFileChooser();
		jFileChooser.setToolTipText("选择结果输出文件");
		jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		jFileChooser.setMultiSelectionEnabled(false);

		jFileChooser.showOpenDialog(null);
		File file = jFileChooser.getSelectedFile();
		if (file != null) {

			String keyFile = textkeyFile.getText();

			ArrayList<String> words = new ArrayList<String>();
			Iterator<String> iterator = setWord.iterator();
			while (iterator.hasNext()) {
				words.add(iterator.next());
			}
			Collections.sort(words);
			String keyFileStr = "";
			if (keyFile != null && keyFile.trim().length() > 0) {
				// 有 key文件时，采用增量模式，导出的为原来key的基础上增加
				String oldFile = this.readkey(keyFile);
				keyFileStr = oldFile;
				// 取以前最后一个key的code编码，
				int p = oldFile.lastIndexOf(":");
				StringBuilder newword = new StringBuilder();
				if (p > 0) {
					String temp = oldFile.substring(0, p);
					p = temp.lastIndexOf("_");
					if (p > 0) {
						String temp2 = temp.substring(p + 1);
						int i = Integer.valueOf(temp2);
						for (String word : words) {
							if (wordKeys.containsKey(word)) {
								continue;
							}
							i++;
							String key = "code_" + getNum(i);
							newword.append("  ");
							newword.append(key);
							newword.append(": ");
							newword = addKeymarks(newword, word);
							newword.append(word);
							newword = addKeymarks(newword, word);
							newword.append(",\n");
						}
					}

				}
				if (newword.length() > 0) {
					p = oldFile.lastIndexOf(":");
					if (p > 0) {
						String temp = oldFile.substring(p);
						int p2 = temp.indexOf("\n");
						if (p2 > 0) {
							keyFileStr = oldFile.substring(0, p) + temp.substring(0, p2 + 1) + newword.toString() + "\n};\n";

						}
					}
				}

			} else {
				StringBuilder sbword = new StringBuilder();
				int i = 0;
				//String key = "module.exports = {\n";
				String key = "export default {\n";
				sbword.append(key);
				for (String word : words) {
					i++;
					key = "code_" + getNum(i);
					sbword.append("  ");
					sbword.append(key);
					sbword.append(": ");
					sbword = addKeymarks(sbword, word);
					sbword.append(word);
					sbword = addKeymarks(sbword, word);
					sbword.append(",\n");

					wordKeys.put(word, key);
				}
				sbword.append("\n};\n");
				keyFileStr = sbword.toString();
			}
			outFile(file, keyFileStr);
		}
	}

	private StringBuilder addKeymarks(StringBuilder sb, String word) {
		if (word.indexOf("'") >= 0) {
			sb = sb.append("\"");
		} else {
			sb = sb.append("'");
		}
		return sb;
	}

	/**
	 * 全部替换
	 * 
	 * @throws IOException
	 */
	private void replaceAll() throws IOException {

		if (!isAnalysis) {
			resultMsg.setText("请先分析，再替换");
			return;
		}

		ArrayList<String> words = new ArrayList<String>();
		Iterator<String> iterator = setWord.iterator();
		while (iterator.hasNext()) {
			words.add(iterator.next());
		}

		Collections.sort(words);

		String sourceFileText = sourcePath.getText();
		if (sourceFileText == null || sourceFileText.trim().length() == 0) {
			resultMsg.setText("请先选择替换目录！");
			return;
		}
		final String sourceFile = sourceFileText.trim();
		wordKeys.clear();
		sb.setLength(0);

		btnReplace.setEnabled(false);

		File file_zh = new File(sourceFile + File.separator + "lang" + File.separator + "zh.js");
		File file_en = new File(sourceFile + File.separator + "lang" + File.separator + "en.js");

		StringBuilder sbword_zh = new StringBuilder();
		StringBuilder sbword_en = new StringBuilder();
		int i = 0;
		//String key = "module.exports = {\n";
		String key = "export default {\n";
		sbword_zh.append(key);
		sbword_en.append(key);
		for (String word : words) {
			i++;
			key = "code_" + getNum(i);
			sbword_zh.append("  ");
			sbword_zh.append(key);
			sbword_zh.append(": '");
			sbword_zh.append(word);
			sbword_zh.append("',\n");

			sbword_en.append("  ");
			sbword_en.append(key);
			sbword_en.append(": '");
			sbword_en.append(word);
			sbword_en.append("',\n");

			wordKeys.put(word, key);
		}
		sbword_zh.append("\n};\n");
		sbword_en.append("\n};\n");

		outFile(file_zh, sbword_zh.toString());
		outFile(file_en, sbword_en.toString());

		resultMsg.setText("生成:" + file_en.getAbsolutePath() + "成功！");
		resultMsg.setText("生成:" + file_zh.getAbsolutePath() + "成功！");
		resultArea.setText("开始替换...");

		new Thread(new Runnable() {
			public void run() {
				try {
					replaceAllFile(sourceFile);
					btnReplace.setEnabled(true);
				} catch (IOException e) {
					e.printStackTrace();
					btnReplace.setEnabled(true);
				}
				resultMsg.setText("替换完成！");
			}
		}).start();

	}

	private String getNum(int num) {
		int length = KEY_NUMBER_LENGTH;
		StringBuilder sb = new StringBuilder();

		String si = String.valueOf(num);
		int l = si.length();
		if (l < length) {
			for (int i = length; i > l; i--) {
				sb.append("0");
			}
			sb.append(si);
		} else if (l == length) {
			return si;
		} else if (l > length) {
			return si.substring(0, length);
		}

		return sb.toString();
	}

	private void replaceAllFile(String path) throws IOException {

		File file = new File(path);
		if (file.isFile()) {
			replaceFile(file.getCanonicalPath());
		} else {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					replaceAllFile(files[i].toString());
				} else {
					if (!files[i].isDirectory()) {
						String fileName = files[i].getName();
						String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
						if (fileType.equalsIgnoreCase("vue") || fileType.equalsIgnoreCase("js") || fileType.equalsIgnoreCase("java")) {
							replaceFile(files[i].getCanonicalPath());
						}
					}
				}
			}
		}

	}

	/**
	 * 替换文件
	 * 
	 * @param path
	 * @throws IOException
	 */
	private void replaceFile(String path) throws IOException {
		if (checkIgnore(path)) {
			return;
		}
		resultMsg.setText("正在处理：" + path);
		sb.append("正在处理：").append(path).append("\n");

		allFileNumber = allFileNumber + 1;
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		// 当前文件中的内容
		StringBuilder sbFile = new StringBuilder();

		ArrayList<String> words = new ArrayList<String>();
		try {
			fis = new FileInputStream(path);
			isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			String templine = "";
			// 是否注释部分
			boolean isAnnotate = false;
			// 是否为vue的 script部分
			boolean isScriptPart = false;
			// 是否模板字符部分 - 用`包括的部分,
			// 如果当前不是是模板字符部分(isTampleStrPart = false)，当前行有奇数个 `，则 isTampleStrPart =
			// true，当前行有偶数个 `，则 isTampleStrPart = false ，
			// 如果当前是是模板字符部分(isTampleStrPart = true)，当前行有奇数个 `则 isTampleStrPart =
			// false，，当前行有偶数个 `，则 isTampleStrPart = true
			boolean isTampleStrPart = false;
			int lineNumber = 0;
			while ((line = br.readLine()) != null) {
				lineNumber = lineNumber + 1;
				templine = line.trim();
				if (isIgnoreLine(templine)) {
					sbFile.append(line).append("\n");
					continue;
				}
				if (templine.startsWith("<!--")) {
					sbFile.append(line).append("\n");
					if (templine.endsWith("-->")) {
						isAnnotate = false;
					} else {
						isAnnotate = true;
					}
					continue;
				} else if (templine.startsWith("/**")) {
					sbFile.append(line).append("\n");
					if (templine.endsWith("*/")) {
						isAnnotate = false;
					} else {
						isAnnotate = true;
					}
					continue;
				} else if (templine.startsWith("/*")) {
					sbFile.append(line).append("\n");
					if (templine.endsWith("*/")) {
						isAnnotate = false;
					} else {
						isAnnotate = true;
					}
					continue;
				}
				if (isAnnotate) {
					sbFile.append(line).append("\n");
					int p = line.indexOf("-->");
					if (p >= 0) {
						isAnnotate = false;
					} else {
						p = line.indexOf("*/");
						if (p >= 0) {
							isAnnotate = false;
						}
					}
					continue;
				}
				if (path.endsWith(".vue")) {
					if (line.trim().equalsIgnoreCase("<script>")) {
						isScriptPart = true;
					} else if (line.trim().equalsIgnoreCase("</script>")) {
						isScriptPart = false;
					}
				}

				words.clear();
				words = getLineWord(line, words);
				// 单词按长的在前排序
				words = orderWords(words);
				if (words.size() > 0) {
					line = replaceLine(words, line, path, isScriptPart, lineNumber, isTampleStrPart);
				}

				sbFile.append(line).append("\n");

				// 如果当前不是是模板字符部分(isTampleStrPart = false)，当前行有奇数个 `，则 isTampleStrPart =true
				// 当前行有偶数个 `，则 isTampleStrPart = false ，
				// 如果当前是是模板字符部分(isTampleStrPart = true)，当前行有奇数个 `则 isTampleStrPart = false
				// 当前行有偶数个 `，则 isTampleStrPart = true
				if (isTampleStrPart) {
					if (isOddnumber(templine)) {
						isTampleStrPart = true;
					} else {
						isTampleStrPart = false;
					}
				} else {
					if (isOddnumber(templine)) {
						isTampleStrPart = true;
					} else {
						isTampleStrPart = false;
					}
				}
			}

			// 回写这个文件
			File fileOut = new File(path);
			outFile(fileOut, sbFile.toString());
			sb.append(fileOut.getAbsolutePath() + "处理完成！\n");
			resultArea.setText(sb.toString());

			fileNumber = fileNumber + 1;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private String replaceLine_ones(ArrayList<String> words, String line, String path, boolean isScriptPart, int lineNumber, boolean isTampleStrPart) {
		for (String word : words) {
			String key = wordKeys.get(word);
			if (key == null || key.trim().length() == 0) {
				continue;
			}
			int p = line.indexOf(word);
			String tempbefor = "";
			if (p >= 0) {
				String beforline = line.substring(0, p).trim();
				tempbefor = line.substring(0, p);
				String endline = line.substring(p + word.length()).trim();
				String errReason = "";

				if (beforline.contains("//")) { // 后注释部分
					break;
				}

				errReason = getErrorReason(beforline, endline, errReason);
				// 有问题的不能替换
				if (errReason.length() > 0) {
					break;
				}
				boolean isReplaced = false;
				if (isTampleStrPart || beforline.indexOf("`") >= 0) {
					// 模板内容 或者本行有模板内容
					if (isTampleStrPart) {
						// 模板内容
						if (isOddnumber(tempbefor)) {// 前面有奇数个
							// 非模板内容

						} else {
							// 模板内容
							line = tempbefor + "${this.$t('" + key +"','"+word + "')}" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
							isReplaced = true;
						}
					} else {
						// 本行有模板内容
						if (isOddnumber(tempbefor)) {
							// 模板内容
							line = tempbefor + "${this.$t('" + key+"','"+word + "')}" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
							isReplaced = true;
						} else {

						}
					}
				}
				if (isReplaced) {
					// do nothing
				} else if (beforline.endsWith("\"")) {
					// String replacement = "\\$t\\('" + key + "'\\)";
					line = tempbefor + "$t('" + key +"','"+word + "')" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
				} else if (beforline.endsWith("'")) {
					// String replacement = "\\$t\\('" + key + "'\\)";
					// line = line.replaceAll(word, replacement);
					tempbefor = tempbefor.substring(0, tempbefor.length() - 1);

					if (tempbefor.trim().endsWith(":")) {
						if (path.endsWith(".js")) {
							line = tempbefor + "vm.$t('" + key +"','"+word  + "')" + replaceLine(words, endline.substring(1), path, isScriptPart, lineNumber, isTampleStrPart);
						} else {
							line = tempbefor + "this.$t('" + key +"','"+word + "')" + replaceLine(words, endline.substring(1), path, isScriptPart, lineNumber, isTampleStrPart);
						}
					} else {
						line = tempbefor + "$t('" + key +"','"+word + "')" + replaceLine(words, endline.substring(1), path, isScriptPart, lineNumber, isTampleStrPart);
					}

				} else if (beforline.endsWith(">")) {
					// String replacement = "{{\\$t\\('" + key + "'\\)}}";
					// line = line.replaceAll(word, replacement);
					line = tempbefor + "{{ $t('" + key +"','"+word  + "') }}" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
				} else if (beforline.endsWith(":")) {
					line = tempbefor + "this.$t('" + key+"','"+word  + "')" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
				} else if (beforline.trim().length() == 0 && !isScriptPart) { // 模板部分，前面空
					line = tempbefor + "{{ $t('" + key+"','"+word + "') }}" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
//				} else if (beforline.indexOf("`") >=0 ) {
//					// todo
//					line = tempbefor + "${this.$t('" + key + "')}" + endline;
				} else if (isScriptPart) {
					// vue里的js部分，都增加this.
					line = tempbefor + "this.$t('" + key +"','"+word + "')" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
				} else {
					line = tempbefor + "{{ $t('" + key +"','"+word + "') }}" + replaceLine(words, endline, path, isScriptPart, lineNumber, isTampleStrPart);
				}

				sb.append("替换第").append(lineNumber).append("行：[ ").append(word).append(" ] 为");
				sb.append(" [ ").append(key+"','"+word).append(" ] ").append("\n");

				//p = line.indexOf(word);

			}
		}
		return line;
	}

	
	private String replaceLine (ArrayList<String> words, String line, String path, boolean isScriptPart, int lineNumber, boolean isTampleStrPart) {
		for (String word : words) {
			String key = wordKeys.get(word);
			if (key == null || key.trim().length() == 0) {
				continue;
			}
			int p = line.indexOf(word);
			String tempbefor = "";
			while (p >= 0) {
				String beforline = line.substring(0, p).trim();
				tempbefor = line.substring(0, p);
				String endline = line.substring(p + word.length()).trim();
				String errReason = "";

				if (beforline.contains("//")) { // 后注释部分
					break;
				}

				errReason = getErrorReason(beforline, endline, errReason);
				// 有问题的不能替换
				if (errReason.length() > 0) {
					break;
				}
				boolean isReplaced = false;
				if (isTampleStrPart || beforline.indexOf("`") >= 0) {
					// 模板内容 或者本行有模板内容
					if (isTampleStrPart) {
						// 模板内容
						if (isOddnumber(tempbefor)) {// 前面有奇数个
							// 非模板内容

						} else {
							// 模板内容
							line = tempbefor + "${this.$t('" + key + "')}" + endline;
							isReplaced = true;
						}
					} else {
						// 本行有模板内容
						if (isOddnumber(tempbefor)) {
							// 模板内容
							line = tempbefor + "${this.$t('" + key + "')}" + endline;
							isReplaced = true;
						} else {

						}
					}
				}
				if (isReplaced) {
					// do nothing
				} else if (beforline.endsWith("\"")) {
					// String replacement = "\\$t\\('" + key + "'\\)";
					line = tempbefor + "$t('" + key + "')" + endline;
				} else if (beforline.endsWith("'")) {
					// String replacement = "\\$t\\('" + key + "'\\)";
					// line = line.replaceAll(word, replacement);
					tempbefor = tempbefor.substring(0, tempbefor.length() - 1);

					if (tempbefor.trim().endsWith(":")) {
						if (path.endsWith(".js")) {
							line = tempbefor + "vm.$t('" + key + "')" + endline.substring(1);
						} else {
							line = tempbefor + "this.$t('" + key + "')" + endline.substring(1);
						}
					} else {
						line = tempbefor + "$t('" + key + "')" + endline.substring(1);
					}

				} else if (beforline.endsWith(">")) {
					// String replacement = "{{\\$t\\('" + key + "'\\)}}";
					// line = line.replaceAll(word, replacement);
					line = tempbefor + "{{ $t('" + key + "') }}" + endline;
				} else if (beforline.endsWith(":")) {
					line = tempbefor + "this.$t('" + key + "')" + endline;
				} else if (beforline.trim().length() == 0 && !isScriptPart) { // 模板部分，前面空
					line = tempbefor + "{{ $t('" + key + "') }}" + endline;
//				} else if (beforline.indexOf("`") >=0 ) {
//					// todo
//					line = tempbefor + "${this.$t('" + key + "')}" + endline;
				} else if (isScriptPart) {
					// vue里的js部分，都增加this.
					line = tempbefor + "this.$t('" + key + "')" + endline;
				} else {
					line = tempbefor + "{{ $t('" + key + "') }}" + endline;
				}

				sb.append("替换第").append(lineNumber).append("行：[ ").append(word).append(" ] 为");
				sb.append(" [ ").append(key).append(" ] ").append("\n");

				p = line.indexOf(word);

			}
		}
		return line;
	}
	
	private String getErrorReason(String beforline, String afterline, String errReason) {
		if (beforline.endsWith("v-if=\"") || beforline.endsWith("===\"") || beforline.endsWith("==='") || beforline.endsWith("=== \"") || beforline.endsWith("=== '")
				|| beforline.endsWith(".indexOf('") || beforline.endsWith("==\"") || beforline.endsWith("=='") || beforline.endsWith("== \"") || beforline.endsWith("== '")
				|| beforline.endsWith(".indexOf(\"") || beforline.endsWith(".endsWith(\"") || beforline.endsWith(".endsWith('") || beforline.endsWith(".startsWith(\"")
				|| beforline.endsWith(".startsWith('")) {
			errReason = " , 条件判断中有中文字符";
		} else if (beforline.endsWith("src=\"")) {
			errReason = " , 图片或者资源中有中文字符";
		} else if (beforline.endsWith("href=\"")) {
			errReason = " , 链接中有中文字符";
		} else if (beforline.endsWith("url('") || (beforline.endsWith("require('"))) {
			errReason = " , 链接中有中文字符";
		}
		// /.test
		if (afterline.startsWith("/.test")) {
			errReason = " , 中文字符作为正侧表达式";
		}
//		if (beforline.trim().length() ==0) {
//			errReason = " , 中文字符开头";
//		}

		return errReason;
	}

	/**
	 * 奇数个`返回true，偶数个`返回false
	 * 
	 * @return
	 */
	private boolean isOddnumber(String str) {
		StringTokenizer st = new StringTokenizer(str, "`", true);
		Vector<String> vs = new Vector<String>();
		String temp = "";
		while (st.hasMoreTokens()) {
			temp = st.nextToken();
			if ("`".equals(temp)) {
				vs.add(temp);
			}
		}
		int num = vs.size();

		return num % 2 == 1;

	}

	/**
	 * 校验不能通过： 1、图片文件名含中文 2、条件判断含中文
	 * 
	 * @throws IOException
	 */
	private void check() throws IOException {

		String sourceFile = sourcePath.getText();

		if (sourceFile == null || sourceFile.trim().length() == 0) {
			resultMsg.setText("请先选择要校验的文件目录！");
			return;
		}
		sb.setLength(0);
		allFileNumber = 0;
		fileNumber = 0;
		// wordNumber = 0;
		wordProblemNumber = 0;

		new Thread(new Runnable() {
			public void run() {
				try {

					chackAllFile(sourceFile.trim());

					resultArea.setText(sb.toString());

					StringBuilder sbMsg = new StringBuilder();
					sbMsg.append("检查文件数：").append(allFileNumber).append(", ");
					sbMsg.append("有问题的文件数：").append(fileNumber).append(", ");
					sbMsg.append("有问题的中文词数：").append(wordProblemNumber).append(".");

					resultMsg.setText(sbMsg.toString());

					btnReplace.setEnabled(true);

					String out = outPath.getText();
					if (out == null || out.trim().length() == 0) {
						out = sourceFile.trim() + File.separator;
					}
					int p = out.lastIndexOf(File.separator);
					if (p >= 0) {
						out = out.substring(0, p) + File.separator + "checkResult.txt";

						File fileOut = new File(out);

						outPath.setText(fileOut.getAbsolutePath());
						outFile(fileOut, sb.toString());

						System.out.println(fileOut.getAbsolutePath());
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();

	}

	private void chackAllFile(String path) throws IOException {

		File file = new File(path);
		if (file.isFile()) {
			chackFile(file.getCanonicalPath());
		} else {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					chackAllFile(files[i].toString());
				} else {
					if (!files[i].isDirectory()) {
						String fileName = files[i].getName();
						String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
						if (fileType.equalsIgnoreCase("vue") || fileType.equalsIgnoreCase("js") || fileType.equalsIgnoreCase("java")) {
							chackFile(files[i].getCanonicalPath());
						}
					}
				}
			}
		}
	}

	/**
	 * 校验文件
	 * 
	 * @param path
	 * @throws IOException
	 */
	private void chackFile(String path) throws IOException {
		if (checkIgnore(path)) {
			return;
		}
		resultMsg.setText("正在检查：" + path);

		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		// 当前文件中的中文
		StringBuilder sbFile = new StringBuilder();
		// 当前文件中的中文数
		long thisWordNumber = 0;
		// 搜索到的文件数
		allFileNumber = allFileNumber + 1;

		ArrayList<String> words = new ArrayList<String>();
		try {
			fis = new FileInputStream(path);
			isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			boolean isAnnotate = false;
			while ((line = br.readLine()) != null) {
				line = line.trim();
				if (isIgnoreLine(line)) {
					continue;
				}
				if (line.startsWith("<!--")) {
					if (!line.endsWith("-->")) {
						isAnnotate = true;
					}
					continue;
				} else if (line.startsWith("/**")) {
					if (!line.endsWith("*/")) {
						isAnnotate = true;
					}
					continue;
				} else if (line.startsWith("/*")) {
					if (!line.endsWith("*/")) {
						isAnnotate = true;
					}
					continue;
				}
				if (isAnnotate) {
					int p = line.indexOf("-->");
					if (p >= 0) {
						isAnnotate = false;
					} else {
						p = line.indexOf("*/");
						if (p >= 0) {
							isAnnotate = false;
						}
					}
					continue;
				}
				words.clear();
				words = getLineWord(line, words);

				if (words.size() > 0) {

					for (String word : words) {
						int p = line.indexOf(word);
						if (p >= 0) {
							String beforline = line.substring(0, p).trim();
							String afterline = line.substring(p + word.length()).trim();
							String errReason = "";
							errReason = getErrorReason(beforline, afterline, errReason);
							if (errReason.length() > 0) {
								sbFile.append(word).append(errReason);
								sbFile.append("\n");
								wordProblemNumber = wordProblemNumber + 1;
								thisWordNumber = thisWordNumber + 1;
							}
						}

					}

				}
			}
			if (sbFile.length() > 0) {
				fileNumber = fileNumber + 1;
				sb.append(path).append(" ").append(", 有问题的中文数：").append(thisWordNumber);
				sb.append("\n");
				sb.append(sbFile);
				sb.append("\n");
				resultArea.setText(sb.toString());
			}

		} catch (Exception e) {

		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 单词按长的在前排序 解决问题： String line = " seriesName: ['品牌蛋', '非品牌蛋', '总净利润', '净利润'],";
	 * 替换后结果为：seriesName: [$t('code_001'), '非$t('code_001')', $t('code_004'),
	 * 
	 * @param words
	 * @return
	 */
	private ArrayList<String> orderWords(ArrayList<String> words) {

		Collections.sort(words, new Comparator<String>() {
			@Override
			public int compare(String s1, String s2) {
				int num = new Integer(s2.length()).compareTo(new Integer(s1.length()));
				return num;
			}
		});
		return words;
	}

	/**
	 * 输出文件
	 * 
	 * @param file
	 * @param str
	 * @throws IOException
	 */
	private void outFile(File file, String str) throws IOException {

		file.mkdirs();
		try {
			if (file.exists()) {
				file.delete();
			}
			OutputStreamWriter writer = null;
			try {
				writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
				writer.write(str);
			} finally {
				try {
					writer.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
}
